# -*- coding: utf-8 -*
import os
import pickle
import pygame
from src.display.window import Window
from src.loader.config import LoaderConfig
from src.loader.mod import ModLoader
from src.config.reference import DEFAULT_CONFIG
from src.handler.event import EventHandler
from src.handler.sprite import SpriteHandler
from src.handler.keyboard import KeyboardHandler
from src.event.sprite import SpriteRegistryEvent
from src.keyboard.move import MoveLeft, MoveRight, MoveUp, MoveDown
from src.helper.path import PathHelper
from src.game.world import World
from src.generator.flat import FlatWorldGenerator
from src.storage.pso import PSO

class Client:

    def __init__(self):
        pygame.init()
        pygame.key.set_repeat(1, 1)
        self.configuration = self.loadConfig()
        self.width = self.configuration["width"]
        self.height = self.configuration["height"]
        self.flags = self.configuration["flags"]
        self.debug = self.configuration["debug"]
        ModLoader.load(self)
        self.load()
        self.window = Window(self.width, self.height, self.flags, self)
        self.registerSprites()
        SpriteHandler.load()
        self.registerKeys()

    def loadConfig(self):
        try:
            return LoaderConfig.load('client.conf')
        except:
            return LoaderConfig.save('client.conf', DEFAULT_CONFIG)

    def load(self):
        print("load data")
        try:
            data = self.loadWorld()
            print("load world")
        except Exception,e:
            print(e)
            data = self.generateBasicWorld()
            print("generate world")
        self.world = World(self, data)

    def generateBasicWorld(self):
        if not os.path.exists(os.path.join('saves', self.configuration['world']["name"])):
            os.makedirs(os.path.join('saves', self.configuration['world']["name"]))
        worlddata = FlatWorldGenerator.generate(self.configuration["world"]["width"], self.configuration["world"]["height"])
        afile = open(PathHelper.getMainDirectory() + os.path.join('saves', self.configuration['world']["name"],'world.data'), 'wb')
        pickle.dump(worlddata, afile, pickle.HIGHEST_PROTOCOL)
        return worlddata

    def loadWorld(self):
        afile = open(PathHelper.getMainDirectory() + os.path.join('saves',self.configuration['world']["name"],'world.data'), 'r')
        return pickle.load(afile)

    def autosave(self):
        worlddata = PSO()
        self.world.writeToPSO(worlddata)
        afile = open(PathHelper.getMainDirectory() + os.path.join('saves', self.configuration['world']["name"],'world.data'), 'wb')
        pickle.dump(worlddata, afile, pickle.HIGHEST_PROTOCOL)
        print("autosave")

    def update(self):
        self.window.update()
        self.world.update()


    def registerSprites(self):
        SpriteHandler.register("logo", PathHelper.getPath('resources','sprites','logo.png'))
        SpriteHandler.register("player", PathHelper.getPath('resources', 'sprites', 'player.png'))
        SpriteHandler.register("ability", PathHelper.getPath('resources', 'sprites', 'ability.png'))
        SpriteHandler.register("heal", PathHelper.getPath('resources', 'sprites', 'heal.png'))
        SpriteHandler.register("projectile", PathHelper.getPath('resources', 'sprites', 'projectile.png'))
        EventHandler.post(SpriteRegistryEvent())

    def registerKeys(self):
        KeyboardHandler.register(pygame.K_a, MoveLeft())
        KeyboardHandler.register(pygame.K_d, MoveRight())
        KeyboardHandler.register(pygame.K_w, MoveUp())
        KeyboardHandler.register(pygame.K_s, MoveDown())
